package com.zgh.rbac.service;

import com.twetec.cms.common.util.cache.RedisCache;
import com.xxg.util.SystemConstant;
import com.zgh.cache.CacheConstant;
import com.zgh.rbac.module.Menu;
import com.zgh.rbac.module.OrganizationAndRole;
import com.zgh.rbac.module.Role;
import com.zgh.rbac.module.RoleAndOrganization;
import com.zgh.usercenter.module.*;
import com.zgh.usercenter.service.UserCenterProxy;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class RbacProxy {
	
	@Autowired
	private RedisCache redisCache;
	@Autowired
	private UserCenterProxy userCenterProxy;
	
	private static final String ORGANIZATION_BUSINESS="1"; //业务体系
	private static final String ORGANIZATION_OA="2";  //OA体系
	
	private static final String LABOURUNION="1"; //单位
	private static final String DEPARTMENT="2";  // 部门
	
	private static final String  NOT_MEMEBER="1";	//普通人员
	private static final String  MEMBER="2";		//工会人员
    
	
	private static final String  LABOUR="1";	//普通职工
	private static final String  STAFF="2";		//工会工作人员
    
	private static final String DEFAULT_ROLE_LABOUR="1";  //工会职工会员默认角色
	private static final String DEFAULT_ROLE_STAFF="2";  //工作人员默认角色
	private static final String DEFAULT_ROLE_LABOURUNION="3";  //工会默认角色
	private static final String DEFAULT_ROLE_COMMON="4";  //默认角色
	
	private static final String  REDISKEY_ROLES= CacheConstant.RBAC+":roles";
	private static final String  REDISKEY_MENUS= CacheConstant.RBAC+":menus";
	private static final String  REDISKEY_SUPERADMIN= CacheConstant.RBAC+":superAdmin";
	
	private static final String ROLE_DATAPOWER_PERSONAL="1";
	private static final String ROLE_DATAPOWER_LABOURUNION="2";
	private static final String ROLE_DATAPOWER_LABOURUNION_CHILD="3";
	private static final String ROLE_DATAPOWER_ALL="4";
	private static final String ROLE_DATAPOWER_CUSTOM="5";
	private static final String ROLE_DATAPOWER_DEPARTMENT="6";
	private static final String ROLE_DATAPOWER_DEPARTMENT_CHILD="7";
	
	private static final String  REDISKEY_DATAPOWER_OF_MENU="dataPower:menu:";  //有权限的菜单
	private static final String  REDISKEY_DATAPOWER_OF_ORG="dataPower:org:";  //数据权限-组织
	private static final String  REDISKEY_DATAPOWER_OF_USER="dataPower:user:"; //数据权限-用户
	private static final String  REDISKEY_DATAPOWER_OF_BIG_ORG="dataPower:bigOrg:";  //有权限的业务单位
	private static final String  REDISKEY_DATAPOWER_OF_BIG_OA_ORG="dataPower:bigOaOrg:";  //有权限的OA单位
	
	//检查是否超级管理员
	public boolean checkIfSuperAdmin(long userId){
		if(userId<=0){
			return false;
		}
		
		String superAdmin=redisCache.getString(REDISKEY_SUPERADMIN);
		if(StringUtils.isNotBlank(superAdmin)){
			String[] strs=superAdmin.split(",");
			for(String str:strs){
				str=str.trim();
				if(str.equals(String.valueOf(userId))){
					return true;
				}
			}
		}
		return false;
	}
	
	//查询出所有的菜单，systemName： 内网系统或者外网系统，pcOrApp：pc或者App
	public List<Menu> listAllMenu(String systemName, String pcOrApp){

		List<Menu> returnList=new ArrayList<Menu>();
		Collection menus=redisCache.getMap(REDISKEY_MENUS).values();
		if(menus==null || menus.isEmpty()){
			return returnList;
		}
		for(Object obj:menus){
			Menu menu=(Menu)obj;
			if(!SystemConstant.YES_STRING.equals(menu.getStatus()) || SystemConstant.YES_STRING.equals(menu.getDeleteStatus())){
				continue;
			}
			if(StringUtils.isNotBlank(systemName) && !systemName.equals(menu.getSystemName())){
				continue;
			}
			if(StringUtils.isNotBlank(pcOrApp) && !pcOrApp.equals(menu.getSort())){
				continue;
			}
			returnList.add(menu);
		}
		return returnList;
	}

	// 获取所有的角色
	public List<Role> listRole() {
		Collection roles =  redisCache.getMap(REDISKEY_ROLES).values();
		Iterator iterator = roles.iterator();
		List<Role> roleList = new ArrayList<>();
		while (iterator.hasNext()) {
			roleList.add((Role) iterator.next());
		}

		return roleList;
	}

	//查询出工会法人默认角色的菜单
	public List<Menu> listLabourUnionMenu(Long labourUnionId, String pcOrApp){
		List<Menu> returnList=new ArrayList<Menu>();
	
		Collection allRoles=redisCache.getMap(REDISKEY_ROLES).values();
		if(allRoles==null || allRoles.isEmpty()){
			return returnList;
		}
		for(Object obj:allRoles){
			Role role=(Role)obj;
			if(DEFAULT_ROLE_LABOURUNION.equals(role.getDefaultType())){
				List<Long> menuIds= role.getMenuIds();
				if(menuIds==null || menuIds.isEmpty()){
					return returnList;
				}
				
				List<Menu> allMenus=this.listAllMenu(ORGANIZATION_BUSINESS, pcOrApp);
				for(Long menuId:menuIds){
					for(Menu menu:allMenus){
						if(menu.getId().equals(menuId)){
							returnList.add(menu);
						}
					}	
				}
				break;
			}
		}
		return  returnList;
	}
	
	public List<Menu> listDefaultBusinessMenu(String systemName, String pcOrApp){
		return this.listDefaultRoleMenu(DEFAULT_ROLE_COMMON, systemName, pcOrApp);
	}
	
	public List<Menu> listDefaultOaMenu(String systemName, String pcOrApp){
		return this.listDefaultRoleMenu(DEFAULT_ROLE_STAFF, systemName, pcOrApp);
	}
	
	//查询出默认角色的菜单
	private List<Menu> listDefaultRoleMenu(String defaultType, String systemName, String pcOrApp){
		List<Menu> returnList=new ArrayList<Menu>();
		if(StringUtils.isBlank(defaultType)){
			return returnList;
		}
		Collection allRoles=redisCache.getMap(REDISKEY_ROLES).values();
		if(allRoles==null || allRoles.isEmpty()){
			return returnList;
		}
		for(Object obj:allRoles){
			Role role=(Role)obj;
			if(defaultType.equals(role.getDefaultType())){
				List<Long> menuIds= role.getMenuIds();
				if(menuIds==null || menuIds.isEmpty()){
					return returnList;
				}
				
				List<Menu> allMenus=this.listAllMenu(systemName, pcOrApp);
				for(Long menuId:menuIds){
					for(Menu menu:allMenus){
						if(menu.getId().equals(menuId)){
							returnList.add(menu);
						}
					}	
				}
				break;
			}
		}
		return  returnList;
	}
	
	public List<Menu> listMenu(long userId, String systemName, String pcOrApp){
		if(userId<=0){
			return listDefaultBusinessMenu(systemName, pcOrApp);
		}

		if(checkIfSuperAdmin(userId)){
			List<Menu> returnList=this.listAllMenu(systemName, pcOrApp);
			return returnList;
		}

		List<Menu> menus=redisCache.getList(REDISKEY_DATAPOWER_OF_MENU+userId);
		
		if(menus==null || menus.isEmpty()){
			menus=listMenuByRedis(userId,null,null);
			redisCache.delete(REDISKEY_DATAPOWER_OF_MENU+userId);
			redisCache.setList(REDISKEY_DATAPOWER_OF_MENU+userId, menus);
		}
		if(StringUtils.isBlank(systemName) || StringUtils.isBlank(pcOrApp)){
			return menus;
		}
		
		List<Menu> returnList=new ArrayList<Menu>();
		for(Object obj:menus){
			Menu menu=(Menu)obj;
			if(StringUtils.isNotBlank(systemName) && !systemName.equals(menu.getSystemName())){
				continue;
			}
			if(StringUtils.isNotBlank(pcOrApp) && !pcOrApp.equals(menu.getSort())){
				continue;
			}
			returnList.add(menu);
		}
		return returnList;
	}
	
		
	//查询出登录用户的菜单，顺便查询出登录用户的数据权限,并将数据权限缓存起来
	private List<Menu> listMenuByRedis(long userId, String systemName, String pcOrApp){
		
		//清理缓存，将数据权限缓存清空
		redisCache.delete(REDISKEY_DATAPOWER_OF_ORG+userId);
		redisCache.delete(REDISKEY_DATAPOWER_OF_USER+userId);
		redisCache.delete(REDISKEY_DATAPOWER_OF_BIG_ORG+userId);
		redisCache.delete(REDISKEY_DATAPOWER_OF_BIG_OA_ORG+userId);

		//如果是超级管理员,则全部展现
		if(checkIfSuperAdmin(userId)){
			List<Menu> returnList=this.listAllMenu(systemName, pcOrApp);
			return returnList;
		}
		//获取最基本的默认权限	
		List<Menu> returnList=listDefaultBusinessMenu(systemName, pcOrApp);
		
		//如果登录人为空
		if(userId<=0){
			return returnList;
		}
	
		//获取用户信息
		User user=userCenterProxy.getUser(userId);
		//如果用户不存在，直接返回默认权限
		if(user==null){  
			return returnList;
		}
		
		//用户所在业务部门的权限
		StringBuffer powerBusinessDepartmentCodes=new StringBuffer();
		//用户所在业务单位的权限
		StringBuffer powerBusinessLabourUnionCodes=new StringBuffer();
		
		List<UserAndOrganization> userAndOrganizations=user.getUserAndOrganizations();
		if(userAndOrganizations!=null && !userAndOrganizations.isEmpty()){
			for(UserAndOrganization uao:userAndOrganizations){
				Organization or=userCenterProxy.getOrganization(uao.getOrganizationId());
				if(or==null){
					continue;
				}
				if(LABOURUNION.equals(or.getOrganizationType())){
					if(powerBusinessLabourUnionCodes.length()>0){
						powerBusinessLabourUnionCodes.append(",");
					}
					powerBusinessLabourUnionCodes.append(or.getOrganizationCode());
					if(StringUtils.isNotBlank(or.getOldOrganizationCode())){
						powerBusinessLabourUnionCodes.append(",").append(or.getOldOrganizationCode());
					}
				}
				
				if(DEPARTMENT.equals(or.getOrganizationType())){
					if(powerBusinessDepartmentCodes.length()>0){
						powerBusinessDepartmentCodes.append(",");
					}
					powerBusinessDepartmentCodes.append(or.getOrganizationCode());
					if(StringUtils.isNotBlank(or.getOldOrganizationCode())){
						powerBusinessDepartmentCodes.append(",").append(or.getOldOrganizationCode());
					}
				}
			}
		}
		
		//用户所在OA部门的权限
		StringBuffer powerOaDepartmentCodes=new StringBuffer();
		//用户所在OA单位的权限
		StringBuffer powerOaLabourUnionCodes=new StringBuffer();
		
		List<UserAndOaOrganization> userAndOaOrganizations=user.getUserAndOaOrganizations();
		if(userAndOaOrganizations!=null && !userAndOaOrganizations.isEmpty()){
			for(UserAndOaOrganization uaoao:userAndOaOrganizations){
				OaOrganization oaor=userCenterProxy.getOaOrganization(uaoao.getOrganizationId());
				if(oaor==null){
					continue;
				}
				if(LABOURUNION.equals(oaor.getOrganizationType())){
					if(powerOaLabourUnionCodes.length()>0){
						powerOaLabourUnionCodes.append(",");
					}
					powerOaLabourUnionCodes.append(oaor.getOrganizationCode());
					if(StringUtils.isNotBlank(oaor.getOldOrganizationCode())){
						powerOaLabourUnionCodes.append(",").append(oaor.getOldOrganizationCode());
					}
				}
				
				if(DEPARTMENT.equals(oaor.getOrganizationType())){
					if(powerOaDepartmentCodes.length()>0){
						powerOaDepartmentCodes.append(",");
					}
					powerOaDepartmentCodes.append(oaor.getOrganizationCode());
					if(StringUtils.isNotBlank(oaor.getOldOrganizationCode())){
						powerOaDepartmentCodes.append(",").append(oaor.getOldOrganizationCode());
					}
				}
			}
		}
		
		//查出用户对应的全部角色
		Collection roles=redisCache.getMap(REDISKEY_ROLES).values();
		if(roles==null || roles.isEmpty()){
			return returnList;
		}
		
		Set<Long> menuIds=new HashSet<Long>();
		
		for(Object obj:roles){
			Role role=(Role)obj;
			if(!SystemConstant.YES_STRING.equals(role.getStatus()) || SystemConstant.YES_STRING.equals(role.getDeleteStatus())){
				continue;
			}

			if(StringUtils.isNotBlank(systemName) && !systemName.equals(role.getSystemName())){
				continue;
			}
			
			//设置工会会员默认权限
			if(DEFAULT_ROLE_LABOUR.equals(role.getDefaultType())  && MEMBER.equals(user.getIfMember())){
				setMenus(menuIds, role,user,
						powerBusinessDepartmentCodes.toString(),powerBusinessLabourUnionCodes.toString(),
						powerOaDepartmentCodes.toString(),powerOaLabourUnionCodes.toString());
				continue;
			}
			
			//设置工会工作人员默认权限
			if(DEFAULT_ROLE_STAFF.equals(role.getDefaultType())  && STAFF.equals(user.getUserType())){
				setMenus(menuIds, role,user,
						powerBusinessDepartmentCodes.toString(),powerBusinessLabourUnionCodes.toString(),
						powerOaDepartmentCodes.toString(),powerOaLabourUnionCodes.toString());
				continue;
			}
			
			
			//如果角色的成员user包含user
			if(role.getUserIds()!=null && role.getUserIds().contains(user.getId())){
				setMenus(menuIds, role,user,
						powerBusinessDepartmentCodes.toString(),powerBusinessLabourUnionCodes.toString(),
						powerOaDepartmentCodes.toString(),powerOaLabourUnionCodes.toString());
				continue;
			}
			
			//首先查找角色的成员组织
			List<OrganizationAndRole> organizationAndRoles=role.getOrganizationAndRoles();
			if(organizationAndRoles==null || organizationAndRoles.isEmpty()){
				continue;
			}
			//如果角色的成员组织包含user
			for(OrganizationAndRole oar:organizationAndRoles){
				if(checkOrganizationAndUser(user,role.getOrganization(),oar.getOrganizationId(),oar.getIncludeChild())){
					setMenus(menuIds, role,user,
							powerBusinessDepartmentCodes.toString(),powerBusinessLabourUnionCodes.toString(),
							powerOaDepartmentCodes.toString(),powerOaLabourUnionCodes.toString());
					break;
				}
			}
			
		}
		
		List<Menu> allMenus=this.listAllMenu(systemName, pcOrApp);

		//将有权限的菜单加入到returnList
		for(Long menuId:menuIds){
			Menu temp=new Menu();
			temp.setId(menuId);
			if(returnList.contains(temp)){
				continue;
			}
			for(Menu menu:allMenus){
				if(menu.getId().longValue()==menuId.longValue()){
					returnList.add(menu);
					break;
				}
			}
		}
		
		//特别设置：如果用户是某个OA单位的管理员或者分管领导，则自动拥有这个组织及其下级单位的权限
		StringBuffer sb=new StringBuffer();
		List<OaLeader> oaLeaders=user.getLeaderOaIds();
		if(oaLeaders!=null && !oaLeaders.isEmpty()){
			for(OaLeader oaLeader:oaLeaders){
				OaOrganization oa=userCenterProxy.getOaOrganization(oaLeader.getOaId());
				if(oa!=null){
					if(sb.length()>0){sb.append(",");}
					sb.append(oa.getOrganizationCode()+"%");
					if(StringUtils.isNotBlank(oa.getOldOrganizationCode())){
						sb.append(",").append(oa.getOldOrganizationCode()+"%");
					}
				}
			}
		}
		
		List<OaManager> oaManagers=user.getManagerOaIds();
		if(oaManagers!=null && !oaManagers.isEmpty()){
			for(OaManager oaManager:oaManagers){
				OaOrganization oa=userCenterProxy.getOaOrganization(oaManager.getOaId());
				if(oa!=null){
					if(sb.length()>0){sb.append(",");}
					sb.append(oa.getOrganizationCode()+"%");
					if(StringUtils.isNotBlank(oa.getOldOrganizationCode())){
						sb.append(",").append(oa.getOldOrganizationCode()+"%");
					}
				}
			}
		}
		//特别设置：重新设置缓存
		String powerOrganizationCodes=sb.toString();
		String oldPowerOrganizationCodes=(String)redisCache.getMapValue(REDISKEY_DATAPOWER_OF_ORG+user.getId().toString(), "common");
		powerOrganizationCodes=setCode(oldPowerOrganizationCodes, powerOrganizationCodes);
		redisCache.addMap(REDISKEY_DATAPOWER_OF_ORG+user.getId().toString(), "common", powerOrganizationCodes);

		return returnList;
	}
	
	private String getPowerUserIds(Role role, User user){
		if(!ROLE_DATAPOWER_CUSTOM.equals(role.getPowerType())){
			return null;
		}
		List<Long> powerUserIds=role.getPowerUserIds();
		if(powerUserIds==null || powerUserIds.isEmpty()){
			return String.valueOf(user.getId());
		}
		StringBuffer sb=new StringBuffer();
		sb.append(user.getId());
		for(Long userId:powerUserIds){
			sb.append(",").append(userId);
		}
		return sb.toString();
	}
	
	private String getPowerOrganizationCodes(Role role, String powerDepartmentCode, String powerLabourUnionCode){
		if(ROLE_DATAPOWER_PERSONAL.equals(role.getPowerType())){
			return null;
		}else if(ROLE_DATAPOWER_LABOURUNION.equals(role.getPowerType())){
			return powerLabourUnionCode;
		}else if(ROLE_DATAPOWER_LABOURUNION_CHILD.equals(role.getPowerType())){
			if(StringUtils.isBlank(powerLabourUnionCode)){
				return null;
			}
			StringBuffer sb=new StringBuffer();
			String strs[]=powerLabourUnionCode.split(",");
			for(String str:strs){
				if(sb.length()>0){
					sb.append(",");
				}
				sb.append(str).append("%");
			}
			return sb.toString();
		}else if(ROLE_DATAPOWER_DEPARTMENT.equals(role.getPowerType())){
			return powerDepartmentCode;
		}else if(ROLE_DATAPOWER_DEPARTMENT_CHILD.equals(role.getPowerType())){
			if(StringUtils.isBlank(powerDepartmentCode)){
				return null;
			}
			StringBuffer sb=new StringBuffer();
			String strs[]=powerDepartmentCode.split(",");
			for(String str:strs){
				if(sb.length()>0){
					sb.append(",");
				}
				sb.append(str).append("%");
			}
			return sb.toString();
		}else if(ROLE_DATAPOWER_ALL.equals(role.getPowerType())){
			return "%";
		}
		//自定义数据权限
		List<RoleAndOrganization> roleAndOrganizations=role.getRoleAndOrganizations();
		if(roleAndOrganizations==null || roleAndOrganizations.isEmpty()){
			return null;
		}
		StringBuffer sb=new StringBuffer();
		for(RoleAndOrganization rao:roleAndOrganizations){
			if(sb.length()>0){
				sb.append(",");
			}
			//自定义权限暂时不考虑针对不同数据的不同权限，认为是针对所有数据的权限
			if(ORGANIZATION_BUSINESS.equals(role.getOrganization())){
				Organization or=userCenterProxy.getOrganization(rao.getOrganizationId());
				sb.append(getCode(or.getOrganizationCode(), or.getOldOrganizationCode(), rao.getIncludeChild()));
			}
			if(ORGANIZATION_OA.equals(role.getOrganization())){
				OaOrganization oaor=userCenterProxy.getOaOrganization(rao.getOrganizationId());
				sb.append(getCode(oaor.getOrganizationCode(),oaor.getOldOrganizationCode(),rao.getIncludeChild()));
			}
		}
		return sb.toString();
	}
	
	private String getBigOrgIdS(Role role, User user){
		Set<Long> set=new HashSet<>();
		
		if(ROLE_DATAPOWER_LABOURUNION.equals(role.getPowerType())){ // 如果权限是本单位
			
			if(ORGANIZATION_BUSINESS.equals(role.getOrganization())){
				List<UserAndOrganization> list=user.getUserAndOrganizations();
				if(list!=null && !list.isEmpty()){
					for(UserAndOrganization uao:list){
						Organization org=userCenterProxy.getOrganization(uao.getOrganizationId());
						if(org==null){
							continue;
						}
						if(org.getBigId()==0){
							set.add(org.getId());
						}else{
							set.add(org.getBigId());
						}
					}
				}
			}
			
			if(ORGANIZATION_OA.equals(role.getOrganization())){
				List<UserAndOaOrganization> list=user.getUserAndOaOrganizations();
				if(list!=null && !list.isEmpty()){
					for(UserAndOaOrganization uaoo:list){
						OaOrganization oa=userCenterProxy.getOaOrganization(uaoo.getOrganizationId());
						if(oa==null){
							continue;
						}
						if(oa.getBigId()==0){
							set.add(oa.getId());
						}else{
							set.add(oa.getBigId());
						}
					}
				}
			}
			
		}else if(ROLE_DATAPOWER_CUSTOM.equals(role.getPowerType())){ // 如果权限是自定义
			
			List<RoleAndOrganization> roleAndOrganizations=role.getRoleAndOrganizations();
			if(roleAndOrganizations==null || roleAndOrganizations.isEmpty()){
				return null;
			}
			for(RoleAndOrganization rao:roleAndOrganizations){
				//如果有包含下级的，不处理
				if(SystemConstant.YES_STRING.equals(rao.getIncludeChild())){
					continue;
				}
				
				//自定义权限暂时不考虑针对不同数据的不同权限，认为是针对所有数据的权限
				if(ORGANIZATION_BUSINESS.equals(role.getOrganization())){
					Organization or=userCenterProxy.getOrganization(rao.getOrganizationId());
					if(or!=null && or.getBigId()==0){
						set.add(or.getId());
					}
				}
				if(ORGANIZATION_OA.equals(role.getOrganization())){
					OaOrganization oaor=userCenterProxy.getOaOrganization(rao.getOrganizationId());
					if(oaor!=null && oaor.getBigId()==0){
						set.add(oaor.getId());
					}
				}
			}
			
		}
		return StringUtils.join(set, ",");
		
	}
	
	private String getCode(String organizationCode,String oldOrganizationCode,String includeChild){
		StringBuffer sb=new StringBuffer(organizationCode);
		if(SystemConstant.YES_STRING.equals(includeChild)){
			sb.append("%");
		}
		if(StringUtils.isNotBlank(oldOrganizationCode)){
			String strs[]=oldOrganizationCode.split(",");
			for(String str:strs){
				sb.append(",").append(str);
				if(SystemConstant.YES_STRING.equals(includeChild)){
					sb.append("%");
				}
			}
		}
		return sb.toString();
		
	}
	
	private String setCode(String oldCode,String newCode){
		if(StringUtils.isBlank(oldCode)){
			return newCode;
		}
		if(StringUtils.isBlank(newCode)){
			return oldCode;
		}
		if("%".equals(oldCode) || "%".equals(newCode)){
			return "%";
		}
		
		String[] oldStrs=oldCode.split(",");
		String[] newStrs=newCode.split(",");
		List<String> olds=new ArrayList<String>();
		olds.addAll(Arrays.asList(oldStrs));
		for(String str:newStrs){
			if(!olds.contains(str)){
				olds.add(str);
			}
		}
		return StringUtils.join(olds, ",");
	}
	
	
	
	private void setMenus(Set<Long> menuIds, Role role, User user,
                          String powerBusinessDepartmentCodes, String powerBusinessLabourUnionCodes,
                          String powerOaDepartmentCodes, String powerOaLabourUnionCodes){
		//设置功能权限
		if(role.getMenuIds()!=null ){
			menuIds.addAll(role.getMenuIds());
		}
		
		//设置数据权限
		String oldPowerOrganizationCodes=(String)redisCache.getMapValue(REDISKEY_DATAPOWER_OF_ORG+user.getId().toString(), "common");
		//如果之前已经有查看全部的权限，直接返回
		if("%".equals(oldPowerOrganizationCodes)){
			return;
		}
		//如果本角色的查看全部的权限，直接设置并返回
		if(ROLE_DATAPOWER_ALL.equals(role.getPowerType())){
			redisCache.addMap(REDISKEY_DATAPOWER_OF_ORG+user.getId().toString(), "common", "%");
			return;
		}
		//该角色的数据权限-用户
		String powerUserIds=getPowerUserIds(role, user);
		//该角色的数据权限-组织
		String powerOrganizationCodes=null;
		//业务单位ID
		String powerBigOrganizationIds=null;
		//OA单位ID
		String powerBigOaOrganizationIds=null;
		
		if(ORGANIZATION_BUSINESS.equals(role.getOrganization())){
			powerOrganizationCodes=getPowerOrganizationCodes(role,
							powerBusinessDepartmentCodes,
							powerBusinessLabourUnionCodes
							);
			powerBigOrganizationIds=getBigOrgIdS(role, user);
		}
		if(ORGANIZATION_OA.equals(role.getOrganization())){
			powerOrganizationCodes=getPowerOrganizationCodes(role,
							powerOaDepartmentCodes,
							powerOaLabourUnionCodes
							);
			powerBigOaOrganizationIds=getBigOrgIdS(role, user);
		}
		
		
		//将数据权限缓存起来
		String oldPowerUserIds=(String)redisCache.getMapValue(REDISKEY_DATAPOWER_OF_USER+user.getId().toString(), "common");
		powerUserIds=setCode(oldPowerUserIds, powerUserIds);
		redisCache.addMap(REDISKEY_DATAPOWER_OF_USER+user.getId().toString(), "common", powerUserIds);
		
		powerOrganizationCodes=setCode(oldPowerOrganizationCodes, powerOrganizationCodes);
		redisCache.addMap(REDISKEY_DATAPOWER_OF_ORG+user.getId().toString(), "common", powerOrganizationCodes);

		String oldPowerBigOrganizationIds=(String)redisCache.getMapValue(REDISKEY_DATAPOWER_OF_BIG_ORG+user.getId().toString(), "common");
		powerBigOrganizationIds=setCode(oldPowerBigOrganizationIds, powerBigOrganizationIds);
		redisCache.addMap(REDISKEY_DATAPOWER_OF_BIG_ORG+user.getId().toString(), "common", powerBigOrganizationIds);
		
		String oldPowerBigOaOrganizationIds=(String)redisCache.getMapValue(REDISKEY_DATAPOWER_OF_BIG_OA_ORG+user.getId().toString(), "common");
		powerBigOaOrganizationIds=setCode(oldPowerBigOaOrganizationIds, powerBigOaOrganizationIds);
		redisCache.addMap(REDISKEY_DATAPOWER_OF_BIG_OA_ORG+user.getId().toString(), "common", powerBigOaOrganizationIds);
		
		
	}
	
	private boolean checkOrganizationAndUser(User user, String organization, long organizationId, String includeChild){
		List<UserAndOrganization> userAndOrganizations=user.getUserAndOrganizations();
		List<UserAndOaOrganization> userAndOaOrganizations=user.getUserAndOaOrganizations();
		if(
			(ORGANIZATION_BUSINESS.equals(organization) && 
					(userAndOrganizations==null ||	userAndOrganizations.isEmpty())
			) ||
			(ORGANIZATION_OA.equals(organization) && 
					(userAndOaOrganizations==null || userAndOaOrganizations.isEmpty())
			)	
		){
			return false;
		}
		
		if(ORGANIZATION_BUSINESS.equals(organization)){
			Organization source=userCenterProxy.getOrganization(organizationId);
			if(source==null){
				return false;
			}
			for(UserAndOrganization uao:userAndOrganizations){
				Organization target=userCenterProxy.getOrganization(uao.getOrganizationId());
				if(target==null){
					continue;
				}
				if(source.getOrganizationCode().equals(target.getOrganizationCode())){
					return true;
				}
				if(SystemConstant.YES_STRING.equals(includeChild) &&
						target.getOrganizationCode().startsWith(source.getOrganizationCode())){
					return true;
				}
			}
		}
		
		if(ORGANIZATION_OA.equals(organization)){
			OaOrganization source=userCenterProxy.getOaOrganization(organizationId);
			if(source==null){
				return false;
			}
			for(UserAndOaOrganization uaoo:userAndOaOrganizations){
				OaOrganization target=userCenterProxy.getOaOrganization(uaoo.getOrganizationId());
				if(target==null){
					continue;
				}
				if(source.getOrganizationCode().equals(target.getOrganizationCode())){
					return true;
				}
				if(SystemConstant.YES_STRING.equals(includeChild) &&
						target.getOrganizationCode().startsWith(source.getOrganizationCode())){
					return true;
				}
			}
		}
		
		return false;
	}
	
	
	public void clearPower(long userId) {
		redisCache.delete(REDISKEY_DATAPOWER_OF_MENU+userId);	
	}


	// 根据用户id获取用户所有角色
	public List<Role> getRoleByUserId(Long userId, String systemName) {
		List<Role> returnList = new ArrayList<>();

		User user = userCenterProxy.getUser(userId);
		//查出用户对应的全部角色
		Collection roles=redisCache.getMap(REDISKEY_ROLES).values();
		if(roles==null || roles.isEmpty()){
			return returnList;
		}

		Set<Long> menuIds=new HashSet<Long>();

		for(Object obj:roles){
			Role role=(Role)obj;
			if(!SystemConstant.YES_STRING.equals(role.getStatus()) || SystemConstant.YES_STRING.equals(role.getDeleteStatus())){
				continue;
			}

			if(StringUtils.isNotBlank(systemName) && !systemName.equals(role.getSystemName())){
				continue;
			}

			//设置工会会员默认权限
			if(DEFAULT_ROLE_LABOUR.equals(role.getDefaultType())  && MEMBER.equals(user.getIfMember())){
				returnList.add(role);
				continue;
			}

			//设置工会工作人员默认权限
			if(DEFAULT_ROLE_STAFF.equals(role.getDefaultType())  && STAFF.equals(user.getUserType())){
				returnList.add(role);
				continue;
			}


			//如果角色的成员user包含user
			if(role.getUserIds()!=null && role.getUserIds().contains(user.getId())){
				returnList.add(role);
				continue;
			}

			//首先查找角色的成员组织
			List<OrganizationAndRole> organizationAndRoles=role.getOrganizationAndRoles();
			if(organizationAndRoles==null || organizationAndRoles.isEmpty()){
				continue;
			}
			//如果角色的成员组织包含user
			for(OrganizationAndRole oar:organizationAndRoles){
				if(checkOrganizationAndUser(user,role.getOrganization(),oar.getOrganizationId(),oar.getIncludeChild())){
					returnList.add(role);
					break;
				}
			}

		}
		return returnList;
	}

}
